/**
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 * <p>
 * PmReceiptApplyService
 * 项目收据申请
 * <p>
 * 修改纪录
 * 2020-05-21 版本：1.0 wushenghong 创建。
 *
 * @version 版本：1.0
 * @author 作者：wushenghong
 * 创建日期：2020-05-21
 */
package com.topscomm.pm.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.MessageException;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.pm.pojo.PmReceiptApplyEntity;
import com.topscomm.pm.service.IPmProjectService;
import com.topscomm.pm.service.IPmReceiptApplyService;
import com.topscomm.pm.service.impl.auto.PmReceiptApplyServiceAuto;
import com.topscomm.pub.util.StringBufferProxy;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@Service(value = "pmReceiptApplyService")
@Scope(value = "singleton")
public class PmReceiptApplyService extends PmReceiptApplyServiceAuto implements IPmReceiptApplyService {
    @Resource(name = "pmProjectService")
    private IPmProjectService pmProjectService;

    /**
     * @param entity
     * @throws
     * @author: wushenghong
     * @date: 2020-05-21
     * @description:单号生成
     * @modify:
     */
    @Override
    protected void beforeInsert(BasicEntity entity) {
        super.beforeInsert(entity);
        if (entity.getId() <= 0) {// 赋值Id和单号
            long[] arrayId = PrimaryKeyUtil.GeneIDs(entity.getTableName(), 1);
            entity.setId(arrayId[0]);
            String docNo = String.valueOf(arrayId[0]);
            docNo = docNo.substring(0, 6) + docNo.substring(9);
            entity.setValue(PmReceiptApplyEntity.FieldDocno, docNo);
        }
    }

    /**
     * @param
     * @throws
     * @author: wushenghong
     * @date: 2020-06-13
     * @description:收据金额计算
     * @modify:
     */
    @Transactional
    public void updateReceiptMoneyOfProjectBase(String sourceId, boolean approvalSuccess) {
        PmReceiptApplyEntity pmReceiptApplyEntity = this.queryById(sourceId);
        if (!approvalSuccess) {// 取消审批回退原单据状态
            if (!ObjectUtil.isEmpty(pmReceiptApplyEntity)) {
                if (!("1".equals(pmReceiptApplyEntity.getCategory()))) {
                    Long oldId = pmReceiptApplyEntity.getOldid();
                    Map<String, Object> updateParam = new HashedMap<>();
                    updateParam.put("id", oldId);
                    updateParam.put("iscancel", '0');
                    this.update(updateParam);
                }
            }
        }
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("select sum(NVL(receiptmoney,0)) as totaladdmoney, sum(NVL(oldreceiptmoney,0)) as totalsubtractmoney from PmReceiptApply where projectid = {0} and state = 9 and id <> {1}", pmReceiptApplyEntity.getProjectid(), sourceId);
        BigDecimal totalMoney = BigDecimal.ZERO;
        if (approvalSuccess) {
            // 新增、作废、重开
            if ("1".equals(pmReceiptApplyEntity.getCategory())) {
                totalMoney = pmReceiptApplyEntity.getReceiptmoney();
            } else if ("2".equals(pmReceiptApplyEntity.getCategory())) {
                totalMoney = pmReceiptApplyEntity.getOldreceiptmoney().negate();
            } else if ("3".equals(pmReceiptApplyEntity.getCategory())) {
                totalMoney = pmReceiptApplyEntity.getReceiptmoney().subtract(pmReceiptApplyEntity.getOldreceiptmoney());
            }
        }
        List<Map<String, Object>> moneyList = this.selectExecute(sql.toString());
        if (moneyList.size() > 0) {
            BigDecimal partAddMoney = (BigDecimal) moneyList.get(0).get("totaladdmoney");
            BigDecimal partSubtractMoney = (BigDecimal) moneyList.get(0).get("totalsubtractmoney");
            totalMoney = totalMoney.add(partAddMoney).subtract(partSubtractMoney);
        }
        // 更新项目表中的金额
        sql.clear();
        sql.appendSingle("update pmproject set receiptmoney = {0} where id = {1}", totalMoney, pmReceiptApplyEntity.getProjectid());
        this.updateExecute(sql.toString());
    }

    /**
     * @author: wudaliang
     * @date: 2021-07-27
     * @param: docNo
     * @param: jsonobject
     * @description: 物流系统更新收据信息
     * @return: void
     * @modify:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateByDeliver(String docNo, JSONObject jsonobject) throws ParseException {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" docno='{0}' and enabled=1 ",docNo);
        PmReceiptApplyEntity pmReceiptApplyEntity = this.queryByWhere(sql.toString()).get(0);
        String expressNo = jsonobject.getString("expressNo");
        String mailType = jsonobject.getString("mailType");
        String sendDate = jsonobject.getString("sendDate");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parse = null;
//        try {
            parse = simpleDateFormat.parse(sendDate);
//        } catch (ParseException e) {
//            e.printStackTrace();
//            throw new MessageException("日期转换失败!");
//        }
        pmReceiptApplyEntity.setCouriernumber(expressNo);
        pmReceiptApplyEntity.setCourier(mailType);
        pmReceiptApplyEntity.setMaildate(parse);
        this.updateEntity(pmReceiptApplyEntity);

    }


    /**
     * @author: wudaliang
     * @date: 2021-07-29
     * @param: sourceDocNo
     * @param: mailNo
     * @param: deliveryTime
     * @param: expressCode
     * @description: 物流系统更新收据信息
     * @return: void
     * @modify:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateReceiptByDelivery(String sourceDocNo, String mailNo, Date deliveryTime, String expressCode)
        throws Exception {
        List<PmReceiptApplyEntity> pmReceiptApplyEntities = this
            .queryByWhere(" docno='" + sourceDocNo + "' and enabled=1 ");
        if(pmReceiptApplyEntities.size()>0){
            PmReceiptApplyEntity pmReceiptApplyEntity = pmReceiptApplyEntities.get(0);
            if(pmReceiptApplyEntity!=null){
                //快递方式
                pmReceiptApplyEntity.setCourier(expressCode);
                pmReceiptApplyEntity.setCouriernumber(mailNo);
                pmReceiptApplyEntity.setMaildate(deliveryTime);
                this.updateEntity(pmReceiptApplyEntity);
            }
        }else{
            throw new Exception("工程系统里没有该单号对应的单据！");
        }
    }

    //    /**
//     * @param
//     * @throws
//     * @author: wushenghong
//     * @date: 2020-07-25
//     * @description:审批通过或者取消审批后，根据收款信息自动回款收据
//     * @modify:
//     */
//    public void updateReceiptReturnMoney(String sourceId, boolean approvalSuccess) {
//        PmReceiptApplyEntity pmReceiptApplyEntityCurrent = this.queryById(sourceId);
//        PmRecBillService pmRecBillService = (PmRecBillService) SpringUtil.getBean("pmRecBillService");
//        StringBufferProxy sql = new StringBufferProxy();
//        sql.appendSingle("select sum(NVL(money,0)) as totalreturnmoney from PmRecBill where projectid = {0} and state = 9", pmReceiptApplyEntityCurrent.getProjectid());
//        List<Map<String, Object>> totalReturnMoneyList = pmRecBillService.selectExecute(sql.toString());
//        sql.clear();
//        // 总回款金额，来自项目收款表
//        BigDecimal totalReturnMoney = BigDecimal.ZERO;
//        if (totalReturnMoneyList.size() > 0) {
//            totalReturnMoney = ConvertUtil.convertToBigDecimal(totalReturnMoneyList.get(0).get("totalreturnmoney"));
//        }
//        // 查询当前项目的所有收据(新增、重开,且没作废的)记录，按收据日期排序
//        sql.appendSingle(" projectid = {0} and state = 9 and category != '2' and iscancel = 0 and id <> {1} order by createon asc", pmReceiptApplyEntityCurrent.getProjectid(), sourceId);
//        List<PmReceiptApplyEntity> pmReceiptApplyEntityList = this.queryByWhere(sql.toString());
//        sql.clear();
//        if (approvalSuccess) {
//            pmReceiptApplyEntityList.add(pmReceiptApplyEntityCurrent);
//        }
//        List<BasicEntity> pmReceiptApplyEntities = new ArrayList<BasicEntity>();
//        if (pmReceiptApplyEntityList.size() > 0 && totalReturnMoney.compareTo(BigDecimal.ZERO) > 0) {
//            for (PmReceiptApplyEntity pmReceiptApplyEntity : pmReceiptApplyEntityList) {
//                if (totalReturnMoney.subtract(pmReceiptApplyEntity.getReceiptmoney()).compareTo(BigDecimal.ZERO) > -1) {
//                    pmReceiptApplyEntity.setReturnmoney(pmReceiptApplyEntity.getReceiptmoney());
//                    pmReceiptApplyEntities.add(pmReceiptApplyEntity);
//                    totalReturnMoney = totalReturnMoney.subtract(pmReceiptApplyEntity.getReceiptmoney());
//                } else {
//                    pmReceiptApplyEntity.setReturnmoney(totalReturnMoney);
//                    pmReceiptApplyEntities.add(pmReceiptApplyEntity);
//                    break;
//                }
//            }
//            this.updateBatch(pmReceiptApplyEntities);
//        }
//    }
}
